/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package TimeRecording.widgets;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFormattedTextField;

/**
 *
 * @author dpatchett
 */
public class DoubleTextField extends JFormattedTextField
        implements FocusListener, Runnable {

    private final static DoubleFormatterFactory
            doubleFormatterFactory = new DoubleFormatterFactory();

    private double oldDouble;

    @SuppressWarnings("LeakingThisInConstructor")
    public DoubleTextField() {
        super(doubleFormatterFactory);
        this.addFocusListener(this);
    }

    @Override
    protected void invalidEdit() {
        setValue(oldDouble);
    }

    public void focusGained(FocusEvent e) {

        // Strange thing with this control is we can't select the text
        // at this point; we have to queue an event to fire in a tick

        oldDouble = (Double)getValue();
        java.awt.EventQueue.invokeLater(new Thread(this));
    }

    public void focusLost(FocusEvent e) {
        try {
            if (getFormatter().stringToValue(getText()) == null) {
                setValue(oldDouble);
            }
        } catch (ParseException ex) {
            Logger.getLogger(DoubleTextField.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void run() {
        this.selectAll();
    }
}
